package com.kinglumi.ailighting.auth.email;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Properties;

/**
 * @Author: wangyinjie
 * @Description:
 * @Date: Created in 20:20 2022/11/1
 * @Modified By:
 */
@Slf4j
@Component
@AllArgsConstructor
public class EmailSenderConfig {

    private final EmailConfig mailConfig;

    private final List<JavaMailSenderImpl> senderList;

    /**
     * 初始化 sender
     */
    @PostConstruct
    public void buildMailSender(){
        List<EmailConfig.MailProperties> mailConfigs = mailConfig.getConfigs();
        log.info("初始化mailSender");
        mailConfigs.forEach(mailProperties -> {

            // 邮件发送者
            JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
            javaMailSender.setDefaultEncoding(mailProperties.getDefaultEncoding());
            javaMailSender.setHost(mailProperties.getHost());
            javaMailSender.setPort(mailProperties.getPort());
            javaMailSender.setProtocol(mailProperties.getProtocol());
            javaMailSender.setUsername(mailProperties.getUsername());
            javaMailSender.setPassword(mailProperties.getPassword());

            Properties properties = new Properties();
            //开启认证
            properties.setProperty("mail.smtp.auth", "true");
            //启用调试
            properties.setProperty("mail.debug", "false");
            //设置链接超时
            properties.setProperty("mail.smtp.timeout", "5000");
            //设置端口
            properties.setProperty("mail.smtp.port", Integer.toString(465));
            //设置ssl端口
            properties.setProperty("mail.smtp.socketFactory.port", Integer.toString(465));
            properties.setProperty("mail.smtp.socketFactory.fallback", "false");
            properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            javaMailSender.setJavaMailProperties(properties);
            // 添加数据
            senderList.add(javaMailSender);
        });
    }

    /**
     * 获取MailSender
     * @return CustomMailSender
     */
    public JavaMailSenderImpl getSender(int app){
        if(senderList.isEmpty()){
            buildMailSender();
        }
        // 随机返回一个JavaMailSender
        return senderList.get(app);
    }

    /**
     * 清理 sender
     */
    public void clear(){
        senderList.clear();
    }

}
